package com.nz.net.hays.www;

import java.util.ArrayList;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.Toast;


public class SignIn extends Activity implements OnClickListener, OnCheckedChangeListener{
	
	
	
		Button login,signin;
		private EditText username,password;
		//public static final String MyPREFERENCES = "MyPrefs" ;
		  // public static final String name = "nameKey"; 
		   //public static final String pass = "passwordKey"; 
		  // SharedPreferences sharedpreferences;
		private ProgressDialog pDialog;
		int flag=0;
		Intent i;
		JSONParser jsonParser = new JSONParser();
		//private static String url = "http://10.0.2.2/rdias/login.php";
		private static String url = "http://hays.byethost6.com/hayslogin.php";
		private static final String TAG_SUCCESS = "success"; 
		@Override
		protected void onCreate(Bundle savedInstanceState) {
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
			.detectDiskReads().detectDiskWrites().detectNetwork()
			.penaltyLog().build());
			super.onCreate(savedInstanceState);
			setContentView(R.layout.signin);
		
			
			
			
		//Go To Signin.java	
		/*	signin=(Button)findViewById(R.id.login);
			
	        signin.setOnClickListener(new View.OnClickListener() 
	        {		
				@Override
				public void onClick(View view) {
					Intent i = new Intent(getApplicationContext(), SignIn.class);
					startActivity(i);
					
				}
			}); */
	    // Close Signin.java
	        
	     //Get all data and log in 
	    	login=(Button)findViewById(R.id.login);	
	    	username=(EditText)findViewById(R.id.edittextusername);
	    	password=(EditText)findViewById(R.id.password);
	    	
	        login.setOnClickListener(new View.OnClickListener() 
	        {			
				@Override
				public void onClick(View view) {
					
			//Check all fields		
					if(username.length()<10)
					{
						Toast.makeText(SignIn.this,"Please Enter correct username", Toast.LENGTH_LONG).show();
						return;
					}
					 if(password.length()<4)
					{				
						Toast.makeText(SignIn.this,"Please Enter correct password", Toast.LENGTH_LONG).show();
						return;
					}
			//check connectivity		
					 if(!isOnline(SignIn.this))
					{					
						Toast.makeText(SignIn.this,"No network connection", Toast.LENGTH_LONG).show();
						return;	
					}
			
			//from login.java		
						new loginAccess().execute();
				}
	   
			//code to check online details
			private boolean isOnline(Context mContext) {
			ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo netInfo = cm.getActiveNetworkInfo();
			if (netInfo != null && netInfo.isConnectedOrConnecting())
		   	  {
				return true;
	     		}
			    return false;
	       	}
	      //Close code that check online details		
		  }); 
	        //Close log in 
	    }

	
	


	class loginAccess extends AsyncTask<String, String, String> {

	private	String user;
	private	String pwd;
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(SignIn.this);
			pDialog.setMessage("Login...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}
		@Override
		protected String doInBackground(String... arg0) {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			user=username.getText().toString();
			pwd=password.getText().toString();
			params.add(new BasicNameValuePair("username", user));
			params.add(new BasicNameValuePair("password", pwd));
			JSONObject json = jsonParser.makeHttpRequest(url,"POST", params);
			Log.d("Create Response", json.toString());
			
			try {
				int success = json.getInt(TAG_SUCCESS);
				//int success=1;
				if (success == 1) 
				 {
					publishProgress("");
				  flag=0;	
				   
				//  i.putExtra("password",pwd);
				 
				 
				 
				 }
				 else
				 {
					// failed to login
					 publishProgress("Incorrect username/password");
					flag=1;
				}
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(SignIn.this,e.getMessage(), Toast.LENGTH_LONG).show();
				
			}
			return null;
		}
		
		 
		protected void onPostExecute(String file_url) {
			try {
				pDialog.dismiss();
				
				if(flag==0)
				{
				com.nz.net.hays.www.MainActivity.loginFlag=0;
					
					 i = new Intent(getApplicationContext(),WelcomeWithDrawerActivity.class);
					 i.putExtra("username",user);
					startActivity(i);
				finish();
				}
				else if(flag==1)
					{
				
				new DialogPopUp().displayDialog(SignIn.this, "Login Error", "Incorrect Login Credentials!!", false);
					//Toast.makeText(SignIn.this,"Please Enter Correct informations", Toast.LENGTH_LONG).show();
					}
				
			} catch (Exception e) {
			
				e.printStackTrace();
			}
			
		}
		
		
	  }
		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			// Inflate the menu; this adds items to the action bar if it is present.
			getMenuInflater().inflate(R.menu.main, menu);
			return true;
		}
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			
		}


		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			// TODO Auto-generated method stub
			
		}
		

	}

